<template>
  <div class="common-layout">
    <el-container>
      <el-header class="header-wrap">
        <div
          v-if="webName == '国天智充' && !orgObj.channelName"
          class="title-wrap"
          @click="clickTitle"
        >
          <div class="img-logo"></div>
          <div class="title1">
            {{ proxy.$config.name }}<br />{{ proxy.$config.title }}
          </div>
        </div>
        <div v-else class="title" @click="clickTitle">
          {{ orgObj.channelName || proxy.$config.name }}<br />{{
            proxy.$config.title
          }}
        </div>
        <div class="iconfont icon-menu" @click="clickShowMenu"></div>
        <div class="right-wrap">
          <div class="box-wrap">
            <div class="iconfont icon-company"></div>
            <div class="text">当前公司：</div>
            <div class="box-cursor">
              <div
                class="text text-bold heard-org-name"
                :class="{ 'heard-org-name-hide': orgObj.isClick }"
              >
                {{ orgObj.name }}
              </div>
              <!-- <div class="iconfont icon-arrow"></div> -->
              <el-cascader
                v-if="orgObj.isClick"
                ref="orgRef"
                class="heard-org"
                v-model="orgObj.id"
                :show-all-levels="false"
                :options="orgObj.options"
                @change="handleChangeOrg"
                placeholder=" "
                :props="{ value: 'id', checkStrictly: true }"
              />
            </div>
          </div>
          <div class="box-wrap">
            <div class="iconfont icon-user"></div>
            <div class="text">当前用户：</div>
            <div class="box-cursor" @click="clickPws">
              <div class="text text-bold">
                {{ accountName }}
              </div>
              <div class="iconfont icon-arrow"></div>
            </div>
          </div>
          <div class="line"></div>
          <div class="box-wrap box-cursor" @click="clickLogout">
            <div class="iconfont icon-logout"></div>
            <div class="text">退出登录</div>
          </div>
        </div>
      </el-header>
      <el-container>
        <el-aside
          class="menu-wrap"
          :class="{
            'menu-wrap1': menuData.mWidth !== 162,
            'menu-wrap2': !menuData.isFirstMenu,
          }"
        >
          <el-scrollbar>
            <div v-if="menuData.mWidth !== 162">
              <div
                class="item-wrap"
                :class="{ 'item-select': menuData.selectIds[0] === item.id }"
                v-for="item in menuList"
                :key="item.id"
                @click="clickIconMenu(item)"
              >
                <div class="name-wrap">
                  <div
                    class="iconfont"
                    :class="`icon-menu-${getIcon(item)}`"
                  ></div>
                </div>
              </div>
            </div>
            <QcMenu
              ref="menuRef"
              v-show="menuData.mWidth === 162"
              :menus="menuList"
              @select-menu="selectMenu"
              @show-submenu="showSubmenu"
              @hide-submenu="hideSubmenu"
            ></QcMenu>
          </el-scrollbar>
        </el-aside>
        <el-main class="main-wrap">
          <!-- 面包屑 -->
          <div v-if="$route.meta.title" class="breadcrumb-wrap">
            <span class="text">{{ getBreadcrumb(1, $route.meta.title) }}</span>
            <span>{{ getBreadcrumb(2, $route.meta.title) }}</span>
          </div>
          <!-- 提示 -->
          <div v-if="$route.meta.tip" class="top-tip-wrap">
            <div class="icon"></div>
            {{ $route.meta.tip }}
          </div>
          <div v-if="$route.meta.title">
            <el-scrollbar class="page-scrollbar">
              <div class="page-wrap">
                <router-view v-slot="{ Component }">
                  <keep-alive :include="cacheRE">
                    <component
                      :is="Component"
                      @clear-cache="clearCache"
                      @get-update="getUpdate"
                      @set-update="setUpdate"
                    />
                  </keep-alive>
                </router-view>
              </div>
            </el-scrollbar>
          </div>
          <router-view
            v-else
            ref="RouterView"
            :key="$route.path"
            @channel-name="setChannelName"
          ></router-view>
          <!-- 备案信息 -->
          <div v-if="icp" class="beian-wrap">
            <a
              class="icp text"
              href="https://beian.miit.gov.cn/"
              target="_blank"
              >{{ icp }}</a
            >
            |
            <div class="text">版权所有 @ {{ company }}</div>
          </div>
        </el-main>
      </el-container>
    </el-container>
    <QcMenu
      v-show="menuData.showSub"
      ref="subMenuRef"
      :menus="menuData.subMenus"
      :parentId="menuData.subParentIds[1]"
      :type="menuData.mWidth === 162 ? 2 : 3"
      @select-sub="selectSub"
      @hide-submenu="hideSubmenu"
      @close-menu="closeMenu"
      @select-menu="selectMenu"
    ></QcMenu>
    <DialogPws ref="dialogPwsRef"></DialogPws>
  </div>
</template>

<script lang="ts" setup>
import QcMenu from './qcmenu.vue';
import DialogPws from './dialogPws.vue';
import { selectOrgTreeData, logout } from '@/service/apis/api';
import { exit, bntAuth } from '@/utils/utils';
import { getIcon } from './menu';
import { cloneDeep } from 'lodash';

const webName = import.meta.env.VITE_ENV_NAME;

const icp = import.meta.env.VITE_ENV_ICP;
const company = import.meta.env.VITE_ENV_COMPANY;

const proxy: any = getCurrentInstance()?.proxy;

// 缓存组件正则，需要缓存的组件，务必配置 name 字段，且满足该正则
let cacheRE = ref(/^.*List$/);
// 清除缓存，一级菜单切换时使用
const clearKeepAliveCache = () => {
  cacheRE.value = new RegExp(`^${Date.now()}$`);
  nextTick(() => {
    cacheRE.value = /^.*List$/;
  });
  isUpdate.value = false;
};
let isUpdate = ref(false);
const clearCache = () => {
  isUpdate.value = true;
};
const getUpdate = (callback: any) => {
  callback(isUpdate.value);
};
const setUpdate = (flag: boolean) => {
  isUpdate.value = flag;
};

const route = useRoute();
const router = useRouter();
const menuRef = ref();
const subMenuRef = ref();

// 判断路径权限
if (route.meta.permission && !bntAuth(route.meta.permission)) {
  ElMessageBox.alert('您没有此模块的权限，请联系管理员', '提示', {
    confirmButtonText: '确认',
    callback: () => {
      exit();
    },
  });
}

const accountName = window.localStorage.getItem('accountName');

const orgRef = ref();
const orgObj = reactive({
  id: '-1',
  name: window.localStorage.getItem('orgName') || '平台',
  options: [] as any,
  isClick: true,
  channelName: '',
});
// 读取缓存中平台信息
const cid = window.localStorage.getItem('channelId');
const oid = window.localStorage.getItem('orgId');
if (oid) {
  orgObj.id = oid;
} else if (cid) {
  orgObj.id = cid;
}

const setChannelName = (str: any) => {
  orgObj.channelName = str;
};

// 树遍历查询
const filterData = (data: any, id: any) => {
  let nameArr: any = {};
  const len = data.length;
  for (let i = 0; i < len; i++) {
    const item = data[i];
    if (item.id === id) {
      nameArr = item;
      break;
    } else if (item.children && item.children.length > 0) {
      nameArr = filterData(item.children, id);
      if (JSON.stringify(nameArr) !== '{}') {
        break;
      }
    }
  }
  return nameArr;
};
// 获取下拉数据
selectOrgTreeData({}).then((res: any) => {
  orgObj.options = res;
  const obj = filterData(res, orgObj.id);
  if (obj && JSON.stringify(obj) !== '{}') {
    if (orgObj.id !== '-1' && !window.localStorage.getItem('orgName')) {
      orgObj.name = obj.label || '';
      window.localStorage.setItem('orgName', orgObj.name);
      window.localStorage.setItem('orgType', res[0].type);
    }
  } else {
    orgObj.name = res[0].label;
    window.localStorage.setItem('orgName', res[0].label);
    orgObj.id = res[0].id;
    if (Number(res[0].id) < 0) {
      window.localStorage.setItem('channelId', '');
      window.localStorage.setItem('orgId', '');
    } else if (Number(res[0].parentId) < 0) {
      window.localStorage.setItem('channelId', orgObj.id || '');
      window.localStorage.setItem('orgId', '');
    } else {
      window.localStorage.setItem('channelId', res[0].referenceId || '');
      window.localStorage.setItem('orgId', orgObj.id || '');
    }
  }
  if (res.length === 1 && res[0].children?.length === 0) {
    orgObj.isClick = false;
  } else {
    orgObj.isClick = true;
  }
});

// 选择平台/渠道/运营商-页面返回欢迎页
const handleChangeOrg = (e: any) => {
  const node = orgRef.value.getCheckedNodes()[0];
  orgObj.name = node.label;
  const data = node.data;
  console.log('e---', orgObj.name, data);
  if (data.parentId === '-100') {
    // 平台
    window.localStorage.setItem('channelId', '');
    window.localStorage.setItem('orgId', '');
    window.localStorage.setItem('orgType', '');
    window.localStorage.setItem('orgName', orgObj.name);
  } else if (data.type === 'CHANNEL') {
    // 渠道
    window.localStorage.setItem('channelId', data.id);
    window.localStorage.setItem('orgId', '');
    window.localStorage.setItem('orgType', 'CHANNEL');
    window.localStorage.setItem('orgName', orgObj.name);
  } else {
    // 企业
    window.localStorage.setItem('channelId', data.referenceId);
    window.localStorage.setItem('orgId', data.id);
    window.localStorage.setItem('orgType', data.type);
    window.localStorage.setItem('orgName', orgObj.name);
  }
  // 清空选中、左侧菜单和浮框菜单数据
  menuRef?.value?.closeMenuId(menuData.subParentIds[0]);
  menuRef?.value?.clearSelectId();
  subMenuRef?.value?.closeMenuId(menuData.selectIds[0]);
  subMenuRef?.value?.clearSelectId();
  menuData.selectIds = [];
  menuData.subMenus = [];
  menuData.subParentIds = [];
  menuData.selectIdHistorys = [];
  menuData.iconMenuSelect = [];

  const channelId = window.localStorage.getItem('channelId');
  if (window.location.pathname !== '/welcome') {
    router.push({
      name: 'welcome',
      query: { channelId: channelId },
    });
  } else {
    router.replace({
      name: 'welcome',
      query: { channelId: channelId },
    });
  }
};

const menuList = JSON.parse(window.localStorage.getItem('menuTree') as string);

// let menuList = reactive([] as any);
// menuList = [
//   {
//     id: '1',
//     name: '用户管理',
//     icon: 'user',
//     children: [
//       {
//         id: '1-1',
//         name: '企业用户',
//         path: 'enterpriseUserList',
//       },
//       {
//         id: '1-2',
//         name: '非企业用户',
//         path: 'noEnterpriseUserList',
//       },
//       {
//         id: '1-3',
//         name: '补贴管理',
//         path: 'subsidyManagementList',
//       },
//       {
//         id: '1-4',
//         name: '订单管理',
//         children: [
//           {
//             id: '1-4-1',
//             name: '实时订单',
//             path: 'userRealTimeOrderList',
//           },
//           {
//             id: '1-4-2',
//             name: '历史订单',
//             path: 'userHistoricalOrderList',
//           },
//         ],
//       },
//     ],
//   },
//   {
//     id: '2',
//     name: '电桩运营',
//     icon: 'equity',
//     children: [
//       {
//         id: '2-1',
//         name: '场站设备管理',
//         children: [
//           {
//             id: '2-1-1',
//             name: '电站管理',
//             path: 'stationList',
//           },
//           {
//             id: '2-1-2',
//             name: '电桩管理',
//             path: 'pileList',
//           },
//           {
//             id: '2-1-3',
//             name: '站点定时调价',
//             path: 'priceTimeList',
//           },
//           {
//             id: '2-1-4',
//             name: '计费模板管理',
//             path: 'priceTemplateList',
//           },
//           {
//             id: '2-1-5',
//             name: '白名单',
//             path: 'whiteList',
//           },
//           {
//             id: '2-1-6',
//             name: '站点评论',
//           },
//         ],
//       },
//       {
//         id: '2-2',
//         name: '互联互通电站',
//       },
//       {
//         id: '2-3',
//         name: '充电卡管理',
//         path: 'chargeCardList',
//       },
//       {
//         id: '2-4',
//         name: '订单管理',
//         children: [
//           {
//             id: '2-4-1',
//             name: '电站实时订单',
//             path: 'realTimeOrderList',
//           },
//           {
//             id: '2-4-2',
//             name: '电站历史订单',
//             path: 'historicalOrderList',
//           },
//           {
//             id: '2-4-3',
//             name: '待处理订单',
//             path: 'pendingOrderList',
//           },
//         ],
//       },
//     ],
//   },
//   {
//     id: '3',
//     name: '营销管理',
//     icon: 'plant-activities',
//     children: [
//       { id: '3-1', name: '用户活动', path: '' },
//       { id: '3-2', name: '优惠券', path: '' },
//       { id: '3-3', name: '电站活动', path: 'stationActivitiesList' },
//       { id: '3-4', name: '通知管理', path: '' },
//       { id: '3-5', name: '广告管理', path: '' },
//       { id: '3-6', name: '常见问题', path: '' },
//       { id: '3-7', name: '标签管理', path: '' },
//     ],
//   },
//   {
//     id: '4',
//     name: '告警中心',
//     icon: 'alarm',
//   },
//   {
//     id: '5',
//     name: '统计中心',
//     children: [
//       { id: '5-1', name: '电站活动', path: 'powerStationStatisticsList' },
//       { id: '5-2', name: '优惠券', path: '' },
//       { id: '5-3', name: '电站活动', path: 'stationActivitiesList' },
//       { id: '5-4', name: '通知管理', path: '' },
//       { id: '5-5', name: '广告管理', path: '' },
//       { id: '5-6', name: '常见问题', path: '' },
//       { id: '5-7', name: '标签管理', path: '' },
//     ],
//   },
//   {
//     id: '6',
//     name: '财务管理',
//     children: [
//       // {
//       //   id: '6-1',
//       //   name: '财务概况',
//       //   path: 'financialOverviewList',
//       // },
//       {
//         id: '6-2',
//         name: '支付渠道对账',
//         path: 'channelReconciliationList',
//       },
//       {
//         id: '6-3',
//         name: '场站分润',
//         children: [
//           {
//             id: '6-3-1',
//             name: '分润汇总',
//             path: 'dividendSummaryList',
//           },
//           {
//             id: '6-3-2',
//             name: '单分润查看',
//             path: 'singleDividendList',
//           },
//           {
//             id: '6-3-3',
//             name: '分润方管理',
//             path: 'dividendManagementList',
//           },
//         ],
//       },
//       {
//         id: '6-4',
//         name: '开票管理',
//         children: [
//           {
//             id: '6-4-1',
//             name: '票务管理',
//             path: 'ticketingManagementList',
//           },
//           {
//             id: '6-4-2',
//             name: '开票审批',
//             path: 'invoicingApprovalList',
//           },
//         ],
//       },
//     ],
//   },
//   {
//     id: '7',
//     name: '企业管理',
//     icon: 'enterprise',
//     children: [
//       {
//         id: '7-1',
//         name: '企业管理',
//         path: 'enterpriseList',
//       },
//     ],
//   },
//   {
//     id: '8',
//     name: '权限管理',
//     icon: 'power',
//     children: [
//       {
//         id: '8-1',
//         name: '角色管理',
//         path: 'roleList',
//       },
//       {
//         id: '8-2',
//         name: '管理员管理',
//         path: 'accountList',
//       },
//     ],
//   },
//   {
//     id: '9',
//     name: '第三方对接',
//   },
//   {
//     id: '10',
//     name: '初始化配置',
//     children: [
//       {
//         id: '10-1',
//         name: '会员等级',
//         path: 'membershipLevelList',
//       },
//       {
//         id: '10-2',
//         name: '系统设置',
//         path: 'systemSettingList',
//       },
//       {
//         id: '10-3',
//         name: '设备信息管理',
//         children: [
//           {
//             id: '10-3-1',
//             name: '品牌管理',
//             path: 'brandManagementList',
//           },
//           {
//             id: '10-3-2',
//             name: '型号管理',
//             path: 'modelManagementList',
//           },
//         ],
//       },
//     ],
//   },
//   {
//     id: '11',
//     name: '平台运营商管理',
//     path: 'platformOperatorList',
//   },
// ];

// 菜单参数
const menuData = reactive({
  mWidth: 162, // 一级菜单宽度
  isFirstMenu: true, // 是否第一次进入，不显示菜单动画
  isMenuArrow: true, // 是否第一次进入，不显示菜单下箭头动画
  showSub: false, // 是否显示子菜单浮框
  selectIds: [] as any, // 选中项ids
  selectIdHistorys: [] as any, //历史选中项ids, 用于取消菜单选择
  subMenus: [] as any, // 选中菜单子集
  subParentIds: [] as any, // 浮框菜单父ids
  iconMenuSelect: [] as any, // 图标菜单选中数据，用于菜单切换模式回填数据
});

// 根据当前路由，菜单赋值
// 树转数组
const treeToArray = (tree: any) => {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i].children) {
      // 每次children有值，就把值合并到原始数据tree上去，增加原始tree，for 循环 的长度也会增加 依次处理...
      tree = tree.concat(tree[i].children);
    }
  }
  return tree;
};
// 获取父子关系的菜单id
const getMenuIds = (flatArray: any, name: string) => {
  let ids: any = [];
  let child = flatArray.find((item: any) => item.referenceId === name);
  ids = [child.id];
  while (child?.parentId && child?.parentId !== '-1') {
    ids = [child.parentId, ...ids];
    child = flatArray.find((item: any) => item.id === child.parentId);
  }
  return ids;
};
const getMenu = () => {
  // 获取当前页面名称
  let pathname = window.location.pathname.replace('/', '');
  if (pathname !== 'welcome') {
    // 获取当前页面对应菜单页面
    const routeList: any = router.options.routes[1].children;
    for (let i = 0; i < routeList?.length; i++) {
      if (routeList[i].name === pathname) {
        pathname = routeList[i].meta.permission.split('.')[0];
        break;
      }
    }
    // 获取父子关系菜单数组
    const ids = getMenuIds(treeToArray(menuList), pathname);
    console.log('ids---', ids);
    // 回填菜单数据
    nextTick(() => {
      const len = ids.length;
      if (menuData.mWidth === 162) {
        const arr = [ids[0], ids[1]];
        menuData.selectIds = [...arr];
        menuData.subParentIds = [...arr];
        if (len > 2) {
          menuRef.value?.selectMenuId(arr[1]);
          menuRef.value?.openMenuId(arr[1]);
          subMenuRef.value?.selectMenuId(ids[2]);
          subMenuRef.value?.openMenuId(ids[2]);
          menuRef.value?.closeMenuId(arr[1]);
        } else if (len > 0) {
          menuRef.value?.selectMenuId(ids[len - 1]);
          menuRef.value?.openMenuId(ids[len - 1]);
        }
      }
    });
  }
};
getMenu();

// 菜单隐藏/显示
const clickShowMenu = () => {
  if (menuData.isFirstMenu) {
    menuData.isFirstMenu = false;
  }
  if (menuData.mWidth === 162) {
    menuData.mWidth = 46;
    // 2-2 变 1-3
    const len = menuData.iconMenuSelect.length;
    if (len > 1) {
      subMenuRef.value?.selectMenuId(menuData.iconMenuSelect[len - 1]);
    }
  } else {
    menuData.mWidth = 162;
    // 1-3 变 2-2
    const len = menuData.iconMenuSelect.length;
    if (len > 2) {
      const arr = [menuData.iconMenuSelect[0], menuData.iconMenuSelect[1]];
      menuRef.value?.selectMenuId(arr[1]);
      menuRef.value?.openMenuId(arr[1]);
      menuData.subParentIds = [...arr];
      menuData.selectIds = [...arr];
      subMenuRef.value?.selectMenuId(menuData.iconMenuSelect[2]);
      subMenuRef.value?.openMenuId(menuData.iconMenuSelect[2]);
      menuRef.value?.closeMenuId(arr[1]);
    } else if (len > 0) {
      menuRef.value?.selectMenuId(menuData.iconMenuSelect[len - 1]);
      menuRef.value?.openMenuId(menuData.iconMenuSelect[len - 1]);
    }
  }
};
// 一级图标菜单点击事件
const clickIconMenu = (item: any) => {
  if (item.children?.length > 0) {
    menuData.showSub = true;
    menuData.subMenus = cloneDeep(item.children);
    menuData.subParentIds = [item.id];
  } else {
    clearKeepAliveCache();
    hideSubmenu();
    menuData.selectIdHistorys = [...menuData.selectIds];
    menuData.subParentIds = [item.id];
    menuData.selectIds = [item.id];
    menuData.iconMenuSelect = [item.id];
    router.push({
      name: item.referenceId,
    });
  }
};
// 一级菜单选择id
const selectMenu = (id: any, type: number = 1) => {
  menuData.iconMenuSelect = [];
  if (type === 1) {
    // 左侧菜单选中菜单
    menuData.selectIds = [...id];
    subMenuRef.value?.selectMenuId('');
    if (menuData.mWidth === 162) {
      menuData.iconMenuSelect = [...id];
    }
    if (menuData.selectIdHistorys[0] !== menuData.selectIds[0]) {
      clearKeepAliveCache();
    }
  } else {
    // 浮框菜单选中菜单
    menuData.selectIds = [...menuData.subParentIds];
    menuRef.value?.selectMenuId(menuData.subParentIds[1]);
    if (menuData.mWidth === 162) {
      menuData.iconMenuSelect = [...menuData.subParentIds, ...id];
    }
    if (menuData.selectIdHistorys[0] !== menuData.subParentIds[0]) {
      clearKeepAliveCache();
    }
  }
};
// 一级菜单关闭id
const closeMenu = () => {
  menuRef.value?.closeMenuId();
};
// 显示二级菜单
const showSubmenu = (data: any) => {
  menuData.showSub = true;
  menuData.subMenus = cloneDeep(data.children);
  menuData.subParentIds = [data.parentId, data.id];
};
// 隐藏二级菜单
const hideSubmenu = () => {
  menuData.showSub = false;
};
// 子菜单选择后，保留选中项
const selectSub = (ids: any) => {
  if (menuData.mWidth !== 162) {
    menuData.selectIds = [...menuData.selectIds, ...ids];
    menuData.iconMenuSelect = [...menuData.selectIds];
  }
  menuData.selectIdHistorys = [...menuData.selectIds];
};

// 显示大屏
const clickTitle = () => {
  if (bntAuth('overView.see')) {
    // 国天新能源用定制大屏
    if (webName === '国天智充') {
      router.push({
        name: 'overViewGtxny',
      });
    } else {
      router.push({
        name: 'overView',
      });
    }
  }
};

// 面包屑显示
const getBreadcrumb = (type: number, title: any) => {
  if (!title) {
    return '';
  }
  const arr = title.split('+');
  if (type === 1) {
    return arr[0];
  }
  let str = '';
  for (let i = 1; i < arr.length; i++) {
    str += `/${arr[i]}`;
  }
  return str;
};

// 退出
const clickLogout = () => {
  ElMessageBox.confirm('是否确定退出登录？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    logout({ accountId: window.localStorage.getItem('accountId') }).then(
      (res: any) => {
        exit();
      }
    );
  });
};

// 修改密码
const dialogPwsRef = ref();
const clickPws = () => {
  dialogPwsRef.value.show();
};
</script>

<style lang="scss" scoped>
@import './main.scss';
</style>
<style lang="scss">
.header-wrap {
  .heard-org {
    position: absolute;
    width: 100%;
    top: -6px;

    &-name {
      width: 100%;
      white-space: nowrap;
    }

    &-name-hide {
      padding-right: 28px;
      visibility: hidden;
    }

    .el-cascader {
      --el-menu-border-color: rgba(0, 0, 0, 0);
      // --el-cascader-menu-fill: rgba(0, 0, 0, 0);
    }

    .el-input {
      --el-input-border-color: rgba(0, 0, 0, 0);
      --el-input-hover-border: rgba(0, 0, 0, 0);
      --el-input-focus-border-color: rgba(0, 0, 0, 0);
      --el-input-hover-border-color: rgba(0, 0, 0, 0);
      --el-input-text-color: #e8e8e8;
    }

    .el-input__wrapper {
      padding: 0 4px;
      background-color: rgba(0, 0, 0, 0);
    }

    .el-icon {
      color: #fff;
    }

    .el-cascader .el-input .icon-arrow-down {
      font-size: 18px;
    }

    .el-input__inner {
      font-weight: bold;
    }
  }
}
</style>